package com.tinyblog.ajax2;

import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;

import java.text.SimpleDateFormat;
import java.io.*;
import java.util.*;

public class AjaxMessageService {
	private Document dom;
	
	public AjaxMessageService() {
		try {
			SAXBuilder builder = new SAXBuilder();
			this.dom = builder.build(AjaxMessageService.class.getResource("ajaxmessages.xml"));
		}catch(Exception ex) {
			this.handleError(ex);
		}
	}
	/**
	 * 重新获取Document对象
	 * @return
	 */
//	public Document initialDocument() {
//		try {
//			SAXBuilder builder = new SAXBuilder();
//			Document dom = builder.build(ClassService.class.getResource("ajaxmessages.xml"));
//		}catch(Exception ex) {
//			this.handleError(ex);
//		}
//		return dom;
//	}
	/**
	 * 获取全部的留言列表
	 * @return
	 */
	public AjaxMessage[] getAllMessage() {
		Collection messages = new ArrayList();
		if(this.dom.getRootElement().getChildren().size()!=0) {
			Iterator iterator = this.dom.getRootElement().getChildren().iterator();
			do {
				Element element = (Element)iterator.next();
				AjaxMessage message = new AjaxMessage(element);
				messages.add(message);
			}while(iterator.hasNext());
			return (AjaxMessage[])messages.toArray(new AjaxMessage[0]);
		}
		else 
			return new AjaxMessage[0];
	}
	/**
	 * 获取全部的留言列表
	 * @return
	 */
	public Map getAllMessageMap() {
		Map messages = new HashMap();
		if(this.dom.getRootElement().getChildren().size()!=0) {
			Iterator iterator = this.dom.getRootElement().getChildren().iterator();
			do {
				Element element = (Element)iterator.next();
				AjaxMessage message = new AjaxMessage(element);
				messages.put(message.getId(),message);
			}while(iterator.hasNext());
		}
		return messages;
	}
	/**
	 * 根据id查找对应的留言
	 * @param id
	 * @return
	 */
	public AjaxMessage getMessage(String id) {
		AjaxMessage ajaxMessage = null;
		Iterator iterator = this.dom.getRootElement().getChildren().iterator();
		do {
			Element element = (Element)iterator.next();
			if(element.getAttributeValue("id").equalsIgnoreCase(id))
				ajaxMessage = new AjaxMessage(element);
		}while(iterator.hasNext());
		return ajaxMessage;
	}
	/**
	 * 添加新留言
	 * @param message
	 */
	public void addMessage(AjaxMessage message) throws Exception {
		Map messages = this.getAllMessageMap();
		message.setId(String.valueOf(messages.size()));
		messages.put(message.getId(),message);
		this.outputXMLDocument((AjaxMessage[])messages.values().toArray(new AjaxMessage[0]));
//		this.dom = this.initialDocument();
	}
	/**
	 * 删除指定的留言
	 * @param messageId
	 */
	public void deleteMessage(String messageId) throws Exception {
		Map messages = this.getAllMessageMap();
		if(messages.containsKey(messageId)) messages.remove(messageId);
		this.outputXMLDocument((AjaxMessage[])messages.values().toArray(new AjaxMessage[0]));
	}
	/**
	 * 更新指定的留言
	 * @param message
	 */
	public void updateMessage(AjaxMessage message) throws Exception {
		Map messages = this.getAllMessageMap();
		if(messages.containsKey(message.getId())) messages.remove(message.getId());
		messages.put(message.getId(),message);
		this.outputXMLDocument((AjaxMessage[])messages.values().toArray(new AjaxMessage[0]));
//		this.dom = this.initialDocument();
	}
	/**
	 * 查找指定的留言
	 * @return
	 */
	public AjaxMessage[] findMessage(MessageCriteria criteria) throws Exception {
		Map messages = new HashMap();
		Map map = this.getAllMessageMap();
		if((map!=null)&&(map.size()!=0)) {
			Iterator iterator = map.values().iterator();
			do {
				AjaxMessage message = (AjaxMessage)iterator.next();
				if((!"".equalsIgnoreCase(criteria.getTitle()))&&(message.getTitle().indexOf(criteria.getTitle())!=-1)) 
					messages.put(message.getId(),message);
				if((!"".equalsIgnoreCase(criteria.getAuthor()))&&(message.getAuthor().indexOf(criteria.getAuthor())!=-1))
					messages.put(message.getId(),message);
				if(!"".equalsIgnoreCase(criteria.getBeginSubmittime())) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					Date beginDate = sdf.parse(criteria.getBeginSubmittime());
					Date messageDate = sdf.parse(message.getSubmittime());
					if(beginDate.compareTo(messageDate)<=0) messages.put(message.getId(),message);
				}
				if(!"".equalsIgnoreCase(criteria.getEndSubmittime())) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					Date endDate = sdf.parse(criteria.getEndSubmittime());
					Date messageDate = sdf.parse(message.getSubmittime());
					if(endDate.compareTo(messageDate)>=0) messages.put(message.getId(),message);
				}
				if((!"".equalsIgnoreCase(criteria.getContent()))&&(message.getContent().indexOf(criteria.getContent())!=-1))
					messages.put(message.getId(),message);
			}while(iterator.hasNext());
			return (AjaxMessage[])messages.values().toArray(new AjaxMessage[0]);
		}else {
			return new AjaxMessage[0];
		}
	}
	/**
	 * 将留言输出为持久化的XML文档
	 *
	 */
	public void outputXMLDocument(AjaxMessage[] messages) throws Exception {
		File file = new File(AjaxMessageService.class.getResource("ajaxmessages.xml").getPath());
		if(file.exists()) file.delete();
		if(!file.exists()) file.createNewFile();
//		System.out.println("路径："+file.getAbsolutePath());
		FileOutputStream stream = new FileOutputStream(file);
		Document doc = new Document();
		Element root = new Element("messages");
		if((messages!=null)&&(messages.length!=0)) {
			for(int i=0;i<messages.length;i++) {
				Element element = new Element("message");
				element.setAttribute("id",messages[i].getId());
				Element title = new Element("title").addContent(messages[i].getTitle());
				Element author = new Element("author").addContent(messages[i].getAuthor());
				Element submittime = new Element("submittime").addContent(messages[i].getSubmittime());
				Element qq = new Element("qq").addContent(messages[i].getQq());
				Element msn = new Element("msn").addContent(messages[i].getMsn());
				Element yahoo = new Element("yahoo").addContent(messages[i].getYahoo());
				Element email = new Element("email").addContent(messages[i].getEmail());
				Element content = new Element("content").addContent(messages[i].getContent());
				element.addContent(title);
				element.addContent(author);
				element.addContent(submittime);
				element.addContent(qq);
				element.addContent(msn);
				element.addContent(yahoo);
				element.addContent(email);
				element.addContent(content);
				root.addContent(element);
			}
		}
		doc.addContent(root);
		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setEncoding("gb2312"));
		outputter.output(doc,stream);
	}
	/**
	 * 输出留言列表为XML文档
	 * @param out
	 */
	public void output(PrintWriter out,AjaxMessage[] ajaxMessages) throws Exception {
		AjaxMessage[] messages = new AjaxMessage[0];
		if(ajaxMessages==null) {
			messages = this.getAllMessage();
		}
		else {
//			this.dom = this.initialDocument();
			messages = ajaxMessages;
		}
		Document doc = new Document();
		Element root = new Element("messages");
		if((messages!=null)&&(messages.length!=0)) {
			for(int i=0;i<messages.length;i++) {
				Element element = new Element("message");
				element.setAttribute("id",messages[i].getId());
				Element title = new Element("title").addContent(messages[i].getTitle());
				Element author = new Element("author").addContent(messages[i].getAuthor());
				Element submittime = new Element("submittime").addContent(messages[i].getSubmittime());
				Element qq = new Element("qq").addContent(messages[i].getQq());
				Element msn = new Element("msn").addContent(messages[i].getMsn());
				Element yahoo = new Element("yahoo").addContent(messages[i].getYahoo());
				Element email = new Element("email").addContent(messages[i].getEmail());
				Element content = new Element("content").addContent(messages[i].getContent());
				element.addContent(title);
				element.addContent(author);
				element.addContent(submittime);
				element.addContent(qq);
				element.addContent(msn);
				element.addContent(yahoo);
				element.addContent(email);
				element.addContent(content);
				root.addContent(element);
			}
		}
		doc.addContent(root);
		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setEncoding("ISO8859-1"));
		outputter.output(doc,out);
	}
	/**
	 * 输出单个的留言为XML文档
	 * @param out
	 * @param message
	 * @throws Exception
	 */
	public void outputSingleMessage(PrintWriter out, AjaxMessage message) throws Exception {
		Document doc = new Document();
		Element root = new Element("messages");
		if(message!=null) {
			Element element = new Element("message");
			element.setAttribute("id",message.getId());
			Element title = new Element("title").addContent(message.getTitle());
			Element author = new Element("author").addContent(message.getAuthor());
			Element submittime = new Element("submittime").addContent(message.getSubmittime());
			Element qq = new Element("qq").addContent(message.getQq());
			Element msn = new Element("msn").addContent(message.getMsn());
			Element yahoo = new Element("yahoo").addContent(message.getYahoo());
			Element email = new Element("email").addContent(message.getEmail());
			Element content = new Element("content").addContent(message.getContent());
			element.addContent(title);
			element.addContent(author);
			element.addContent(submittime);
			element.addContent(qq);
			element.addContent(msn);
			element.addContent(yahoo);
			element.addContent(email);
			element.addContent(content);
			root.addContent(element);
		}
		doc.addContent(root);
		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setEncoding("ISO8859-1"));
		outputter.output(doc,out);
	}
	/**
	 * 处理系统异常
	 * @param ex
	 */
	private void handleError(Exception ex) {
		ex.printStackTrace();
		System.out.println(ex.toString());
	}
	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
//		AjaxMessageService service = new AjaxMessageService();
//		AjaxMessage message = new AjaxMessage();
//		message.setTitle("测试");
//		try {
//			service.addMessage(message);
//		}catch(Exception ex) {
//			System.out.println(ex.toString());
//		}
//		System.out.println(service.getAllMessage().length);
		System.out.println("测试留言功能".indexOf("5878"));
	}
}
